package com.safebus.ui.home;

import java.util.ArrayList;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Context;
import android.location.Location;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;

import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesClient;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.location.LocationClient;
import com.google.android.gms.maps.CameraUpdate;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.gson.Gson;
import com.safebus.R;
import com.safebus.manager.ApiManager;
import com.safebus.manager.ApiManager.DataDownloadListener;
import com.safebus.model.BusModel;

public class HomeActivity extends Activity implements GooglePlayServicesClient.ConnectionCallbacks, 
GooglePlayServicesClient.OnConnectionFailedListener {
	private GoogleMap mMap;

	ApiManager apiManager;

	Context context;

	ArrayList<BusModel> busModelsList = new ArrayList<BusModel>();

	private static final long MIN_TIME = 400;
	private static final float MIN_DISTANCE = 1000;

private LocationClient mLocationClient;
	Thread myThread = null;
	Runnable runnable = null;

	boolean isCancel = true;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_home);

		context = this;
		intializeUI();

		setData();

		/*
		 * final LatLng CIU = new LatLng(35.21843892856462, 33.41662287712097);
		 * Marker ciu = mMap.addMarker(new MarkerOptions().position(CIU).title(
		 * "My Office"));
		 */
	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();

		startThreadListner();

	}

	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		stopThreadListner();
		super.onPause();
	}

	public void startThreadListner() {
		myThread = null;
		runnable = null;
		isCancel = true;
		runnable = new CountDownRunner();
		myThread = new Thread(runnable);
		myThread.start();
	}

	public void stopThreadListner() {
		myThread.interrupt();

		isCancel = false;
	}

	private void setData() {

		apiManager = new ApiManager("http://app.safebusonline.com/",
				new String[] { "" }, new String[] { "" }, false, context);

		apiManager.setDataDownloadListener(new DataDownloadListener() {

			@Override
			public void dataDownloadedSuccessfully(String response) {

				// JsonArray arrayLocation=new
				busModelsList = new ArrayList<BusModel>();

				try {
					JSONArray arrayLocation = new JSONArray(response);
					for (int i = 0; i < arrayLocation.length(); i++) {

						JSONObject jsonObject = arrayLocation.getJSONObject(i);
						BusModel busModel = new BusModel();

						busModel = new Gson().fromJson(jsonObject.toString(),
								BusModel.class);

						busModelsList.add(busModel);
					}

				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

				mMap.clear();

				for (int i = 0; i < busModelsList.size(); i++) {

					double lat = Double.parseDouble(busModelsList.get(i)
							.getLattitude());
					double lng = Double.parseDouble(busModelsList.get(i)
							.getLongitude());

					final LatLng locationPoint = new LatLng(lat, lng);
					Marker markerPoint = mMap.addMarker(new MarkerOptions()
							.position(locationPoint).title(
									busModelsList.get(i).getBus_name()));

					/*CameraUpdate cameraUpdate = CameraUpdateFactory
							.newLatLngZoom(locationPoint, 10);
					mMap.animateCamera(cameraUpdate);*/

				}

			}

			@Override
			public void dataDownloadedError(String err) {

			}
		});
		apiManager.execute();

	}
	@Override
	protected void onStart() {
	    super.onStart();
	    // Connect the client.
	    if(isGooglePlayServicesAvailable()){
	        mLocationClient.connect();
	    }

	}
	
	private boolean isGooglePlayServicesAvailable() {
	    // Check that Google Play services is available
	    int resultCode =  GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
	    // If Google Play services is available
	    if (ConnectionResult.SUCCESS == resultCode) {
	        // In debug mode, log the status
	        Log.d("Location Updates", "Google Play services is available.");
	        return true;
	    } else {
	      

	        return false;
	    }
	}

	private void intializeUI() {

		mMap = ((MapFragment) getFragmentManager().findFragmentById(R.id.map))
				.getMap();
		mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
		
		
		mLocationClient = new LocationClient(this, this, this);
		
		mMap.setMyLocationEnabled(true);

		
	}

	class CountDownRunner implements Runnable {

		public CountDownRunner() {

		}

		// @Override
		public void run() {
			while (true) {
				try {
					doWork();
					Thread.sleep(5000);
				} catch (InterruptedException e) {
					Thread.currentThread().interrupt();
				} catch (Exception e) {
				}

				if (!isCancel) {
					break;
				}
			}
		}

	}

	public void doWork() {
		this.runOnUiThread(new Runnable() {
			public void run() {
				try {

					setData();

				} catch (Exception e) {
					// TextView
					// txtCurrentTime=(TextView)vi.findViewById(R.id.txtAvailability);
					// txtCurrentTime.setText(e.getMessage());
				}
			}
		});
	}

	@Override
	public void onConnectionFailed(ConnectionResult arg0) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void onConnected(Bundle arg0) {
		Toast.makeText(this, "Connected", Toast.LENGTH_SHORT).show();
	    Location location = mLocationClient.getLastLocation();
	    LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
	    CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngZoom(latLng, 15);
	    mMap.animateCamera(cameraUpdate);
		
	}

	@Override
	public void onDisconnected() {
		// TODO Auto-generated method stub
		
	}

	
	
}